#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#define BUFFER_SIZE 1024
#define PIPE_NAME "my_pipe"

int main() {
    int ret = mkfifo(PIPE_NAME, 0666); // 创建命名管道，如果已存在则忽略
    if (ret == -1) {
        perror("mkfifo error");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork(); // 创建子进程
    if (pid == -1) {
        perror("fork error");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) { // 子进程写入数据到命名管道
        int fd = open(PIPE_NAME, O_WRONLY);
        if (fd == -1) {
            perror("open error");
            exit(EXIT_FAILURE);
        }

        char buffer[BUFFER_SIZE] = "Hello, parent! This is child process.";
        if (write(fd, buffer, strlen(buffer) + 1) == -1) { // 向管道中写入数据
            perror("write error");
            exit(EXIT_FAILURE);
        }

        close(fd);
        exit(EXIT_SUCCESS);
    } else { // 父进程从命名管道中读取数据
        int fd = open(PIPE_NAME, O_RDONLY);
        if (fd == -1) {
            perror("open error");
            exit(EXIT_FAILURE);
        }

        char buffer[BUFFER_SIZE];
        int bytesRead = read(fd, buffer, BUFFER_SIZE); // 从管道中读取数据
        if (bytesRead == -1) {
            perror("read error");
            exit(EXIT_FAILURE);
        }

        printf("Received message from child process: %s\n", buffer);

        close(fd);
        exit(EXIT_SUCCESS);
    }
}

